<template>
    <div>
        <!-- 新增与搜索区域 -->
        <div class="header-actions">
            <el-button @click="showAddDialog">新增规则</el-button>
            <el-input v-model="searchQuery" placeholder="搜索规则..." style="width: 200px;" />
        </div>
        
        <!-- 添加表格容器ref -->
        <div ref="tableContainer">
            <el-table :data="filteredRules" border style="width: 100%">
                <!-- 主规则字段 -->
                <el-table-column prop="id" label="规则ID"></el-table-column>
                <el-table-column prop="name" label="规则名称"></el-table-column>
                <el-table-column prop="totalScore" label="总分"></el-table-column>
                <el-table-column prop="createTime" label="创建时间">
                    <template #default="{ row }">
                        {{ formatTime(row.createTime) }}
                    </template></el-table-column>

                <!-- 子规则列表 -->
                <el-table-column width="500px" label="子规则">
                    <template #default="{ row }">
                        <el-table :data="row.subRules" size="small" border>
                            <!-- 题库 -->
                            <el-table-column label="题库">
                                <template #default="{ row: subRow }">
                                    {{ getBankNameById(subRow.bankId) }}
                                </template>
                            </el-table-column>

                            <!-- 题型 -->
                            <el-table-column prop="questionType" label="题型">
                                <template #default="{ row: subRow }">
                                    {{ questionTypeMap[subRow.questionType] }}
                                </template>
                            </el-table-column>

                            <!-- 数量 -->
                            <el-table-column prop="num" label="数量"></el-table-column>

                            <!-- 每题分数 -->
                            <el-table-column prop="perScore" label="每题分数"></el-table-column>
                        </el-table>
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button size="small" type="primary" @click="showEditDialog(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteRule(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="dialogVisible" title="新增规则">
            <el-form :model="newForm" label-width="120px">

                <!-- 主规则字段 -->
                <el-form-item label="规则名称">
                    <el-input v-model="newForm.name" placeholder="请输入名称" />
                </el-form-item>

                <el-form-item label="总分">
                    <el-input v-model.number="newForm.totalScore" placeholder="请输入总分" disabled />
                </el-form-item>

                <!-- 子规则列表 -->
                <el-form-item label="子规则">
                    <el-table :data="newForm.subRules" border size="small">
                        <el-table-column label="题库">
                            <template #default="{ $index }">
                                <el-select v-model="newForm.subRules[$index].bankId" placeholder="请选择题库"
                                    style="width: 100%">
                                    <el-option v-for="bank in banks" :key="bank.id" :label="`${bank.name}`"
                                        :value="bank.id" />
                                </el-select>
                            </template>
                        </el-table-column>

                        <el-table-column label="题型">
                            <template #default="{ $index }">
                                <el-select v-model="newForm.subRules[$index].questionType" placeholder="请选择">
                                    <el-option label="单选题" value="SINGLE" />
                                    <el-option label="判断题" value="JUDGE" />
                                    <el-option label="多选题" value="MULTIPLE" />
                                </el-select>
                            </template>
                        </el-table-column>

                        <el-table-column label="数量">
                            <template #default="{ $index }">
                                <el-input v-model.number="newForm.subRules[$index].num" />
                            </template>
                        </el-table-column>

                        <el-table-column label="每题分数">
                            <template #default="{ $index }">
                                <el-input v-model.number="newForm.subRules[$index].perScore" />
                            </template>
                        </el-table-column>

                        <el-table-column label="操作">
                            <template #default="{ $index }">
                                <el-button size="small" type="danger" @click="removeSubRule($index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-button type="primary" @click="addSubRule">+ 添加子规则</el-button>
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAdd">提交</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="editDialogVisible" title="编辑规则">
            <el-form :model="editForm" label-width="120px">

                <!-- 规则名称 -->
                <el-form-item label="规则名称">
                    <el-input v-model="editForm.name" />
                </el-form-item>

                <!-- 总分 -->
                <el-form-item label="总分">
                    <el-input v-model.number="editForm.totalScore" disabled />
                </el-form-item>

                <!-- 子规则列表 -->
                <el-form-item label="子规则">
                    <el-table :data="editForm.subRules" border size="small">
                        <el-table-column label="题库">
                            <template #default="{ $index }">
                                <el-select v-model="editForm.subRules[$index].bankId" placeholder="请选择题库"
                                    style="width: 100%">
                                    <el-option v-for="bank in banks" :key="bank.id" :label="`${bank.name}`"
                                        :value="bank.id" />
                                </el-select>
                            </template>
                        </el-table-column>

                        <el-table-column label="题型">
                            <template #default="{ $index }">
                                <el-select v-model="editForm.subRules[$index].questionType" placeholder="请选择">
                                    <el-option label="单选题" value="SINGLE" />
                                    <el-option label="判断题" value="JUDGE" />
                                    <el-option label="多选题" value="MULTIPLE" />
                                </el-select>
                            </template>
                        </el-table-column>

                        <el-table-column label="数量">
                            <template #default="{ $index }">
                                <el-input v-model.number="editForm.subRules[$index].num" />
                            </template>
                        </el-table-column>

                        <el-table-column label="每题分数">
                            <template #default="{ $index }">
                                <el-input v-model.number="editForm.subRules[$index].perScore" />
                            </template>
                        </el-table-column>

                        <el-table-column label="操作">
                            <template #default="{ $index }">
                                <el-button size="small" @click="removeEditSubRule($index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-button type="primary" @click="addEditSubRule">+ 添加子规则</el-button>
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEdit">确定修改</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import api from '../services/api';
import { ElLoading, ElMessageBox, ElMessage } from 'element-plus';

const rules = ref([]);
const banks = ref([]);
const searchQuery = ref('');
const dialogVisible = ref(false);
const newForm = ref({
    name: '',
    totalScore: null,
    subRules: []
});
const editDialogVisible = ref(false);
const editForm = ref({
    name: '',
    totalScore: null,
    subRules: []
});

const questionTypeMap = {
    JUDGE: '判断题',
    SINGLE: '单选题',
    MULTIPLE: '多选题'
};

async function fetchRules() {
    const res = await api.getRules(1); // 示例 paperId=1
    rules.value = res.data;
}

async function fetchBanks() {
    const res = await api.getAllBanks();
    banks.value = res.data;
}

function getBankNameById(bankId) {
    const bank = banks.value.find(b => b.id === bankId);
    return bank ? bank.name : '未知题库';
}

function addSubRule() {
    newForm.value.subRules.push({
        bankId: null,
        questionType: '',
        num: 0,
        perScore: 0
    });
}

function removeSubRule(index) {
    newForm.value.subRules.splice(index, 1);
}

function showAddDialog() {
    dialogVisible.value = true;
    if (newForm.value.subRules.length === 0) {
        addSubRule();
    }
}

async function submitAdd() {
    try {
        await api.addPaperRule(newForm.value);
        dialogVisible.value = false;
        resetForm();
        fetchRules(); // 刷新列表
    } catch (error) {
        console.error('新增失败:', error);
    }
}

function resetForm() {
    newForm.value = {
        name: '',
        totalScore: 0,
        subRules: []
    };
}

function showEditDialog(row) {
    // 深拷贝当前行数据到 editForm
    editForm.value = JSON.parse(JSON.stringify(row));
    editDialogVisible.value = true;
}

async function submitEdit() {
    try {
        await api.updatePaperRule(editForm.value.id, editForm.value);
        editDialogVisible.value = false;
        fetchRules(); // 刷新列表
    } catch (error) {
        console.error('编辑失败:', error);
    }
}

function addEditSubRule() {
    editForm.value.subRules.push({
        bankId: null,
        questionType: '',
        num: 0,
        perScore: 0
    });
}

function removeEditSubRule(index) {
    editForm.value.subRules.splice(index, 1);
}

async function deleteRule(ruleId) {
  try {
    await ElMessageBox.confirm('确定删除该规则？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await api.deleteRule(ruleId);
    fetchRules();
    ElMessage.success('规则删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('规则删除失败');
    }
  }
}

const filteredRules = computed(() => {
    const keyword = searchQuery.value.trim().toLowerCase();
    if (!keyword) return rules.value;

    return rules.value.filter(rule =>
        rule.name?.toLowerCase().includes(keyword) ||
        String(rule.id).includes(keyword)
    );
});


// 监听 subRules 变化并计算 totalScore
watch(
    () => newForm.value.subRules,
    (subRules) => {
        calculateTotalScore(subRules, newForm.value);
    },
    { deep: true }
);

// 编辑表单监听 subRules 变化
watch(
    () => editForm.value.subRules,
    (subRules) => {
        calculateTotalScore(subRules, editForm.value);
    },
    { deep: true }
);

// 公共方法：计算总分
function calculateTotalScore(subRules, form) {
    let score = 0;
    for (const rule of subRules) {
        if (rule.num > 0 && rule.perScore > 0) {
            score += rule.num * rule.perScore;
        }
    }
    form.totalScore = score;
}

// 时间格式化函数
function formatTime(timeStr) {
    const date = new Date(timeStr);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

const tableContainer = ref(null);  // 添加表格容器ref

onMounted(async () => {
  const loading = ElLoading.service({
    lock: false,
    target: tableContainer.value,
    text: '数据加载中',
    background: 'rgba(0, 0, 0, 0.3)'
  });
  
  try {
    await Promise.all([fetchRules(), fetchBanks()]);
    // 保证最少显示0.5秒
    setTimeout(() => loading.close(), 500);
  } catch (error) {
    loading.close();
    console.error('初始化数据失败:', error);
  }
});
</script>